<?php
namespace app\admin\controller;

use think\Db;

class Company extends Base {

    /**
     * 企业列表
     */
    public function index(){
        $this->set_tem_val();

        $where = ['is_del'=>0];
        if(input('area_id')){
            $where['area_id'] = input('area_id');
        }elseif(input('city_id')){
            $where['city_id'] = input('city_id');
        }elseif(input('province_id')){
            $where['province_id'] = input('province_id');
        }
        $mobile = I('mobile','');
        $status = I('status',-1);
        //负责人移动电话
        if(!empty($mobile)){
            $where['mobile'] = $mobile;
        }
        if($status != -1){
            $where['status'] = $status;
        }
        input('name') && $where['name'] = ['like','%'.trim(input('name')).'%'];
        input('account') && $where['account'] = ['like','%'.trim(input('account')).'%'];
        input('trade_id') && $where['trade_id'] = input('trade_id');
        input('manage_id') && $where['manage_id'] = input('manage_id');
        input('docking_people') && $where['docking_people'] = trim(input('docking_people'));
        input('docking_mobile') && $where['docking_mobile'] = trim(input('docking_mobile'));
        if(input('start_time')){
            $tem = strtotime(input('start_time'));
            $where['start_time'] = [['>=', $tem], ['<=', $tem+86399], 'and'];
        }
        if(input('export') == 1){
            $this->index_explode($where);
        }
        /*原本模板的到期时间
        $expire_time = date('Y-m-d',strtotime("+".$v['use_time']."year",$v['start_time']));
        $r = strtotime($expire_time) - $v['start_time'];
        echo time_to_str($r);
        */
        $list = db('company')->where($where)->order('id desc')->paginate('',false,page_param());
        $arr_list = $list->items();
        $start_time = strtotime(date('Y-m-01',time()));
        $end_time = strtotime('+1 month',$start_time)-1;
        $year_month = strtotime(date('Y-m',time()));
//        foreach ($arr_list as $key=>$value){
//            //月度人均积分
//            //公司人员总数
//            $people_sum = M('users')->where('com_id',$value['id'])->where('type',1)->count() -1;
//            //公司当月获得总积分
//            $where_a['a.status'] = 2;
//            $where_a['a.prize_buckle_time'] = ['between',[$start_time,$end_time]];
//            $where_a['c.is_cancellation'] = 0;//未作废
//            $where_a['d.type'] = 1;//在职
//            $where_a['d.role_id'] = ['neq',''];//排除管理员
//            $where_a['a.com_id'] = $value['id'];
//            $res = M('com_integral_prize_buckle a')
//                ->join('com_integral_prize_buckle_relation_event b','a.id=b.prize_buckle_id','right')
//                ->join('com_integral_event_relation_users c','c.event_id=b.id','right')
//                ->join('users d','c.user_id=d.id','left')
//                ->where($where_a)
//                ->field('COALESCE(SUM(IF(c.piece_rate=0,c.integral_b,c.piece_rate*c.integral_b)),0) integral_b ')
//                ->find();
//            $total_integral = $res['integral_b'];
//            //公司当月总奖扣人次
//            $where_b = [];
//            $where_b['a.com_id'] = $value['id'];
//            $where_b['a.status'] = 2;
//            $where_b['c.is_cancellation'] = 0;//未作废
//            $where_b['a.prize_buckle_time'] = ['between',[$start_time,$end_time]];
//            $total_prize_buckle_people_sum = M('com_integral_prize_buckle a')
//                ->join('com_integral_prize_buckle_relation_event b','b.prize_buckle_id = a.id','left')
//                ->join('com_integral_event_relation_users c','c.event_id = b.id','left')
//                ->where($where_b)->count('c.id');
//            //月人均得分
//            if(empty($people_sum)){
//                $average_integral = 0;
//                $average_sum = 0;
//            }else{
//                $average_integral = ceil($total_integral/$people_sum);
//                //月人均人次
//                $average_sum = ceil($total_prize_buckle_people_sum/$people_sum);
//            }
//
//            $arr_list[$key]['average_integral'] = $average_integral;
//            $arr_list[$key]['average_sum'] = $average_sum;
//        }
        $addr_ids = array_unique(array_merge(array_column($arr_list, 'province_id'), array_column($arr_list, 'city_id'), array_column($arr_list, 'area_id')));
        $region_list = db('region')->where('id', 'in', $addr_ids)->column('id, name');
        $this->assign('arr_list', $arr_list);
        $this->assign('list', $list);
        $this->assign('region_list', $region_list);
        return $this->fetch();
    }
    //重置企业账号密码
    public function reset(){
        $id = I('id',0);
        if(empty($id)){
            return return_json(1,'企业id不能为空');
        }
        //查询企业账号用户
        $where = [];
        $where['com_id'] = $id;
        $where['role_id'] = null;
        $users = M('users')->where($where)->find();
        M('users')->where('id',$users['id'])->update(['password'=>md5('123456')]);
        return return_json(0,'重置成功');
    }
    public function index_edit(){
        if(request()->isPost()){
            return $this->index_store();
        }
        $this->set_tem_val();
        if(input('id')){
            $info = db('company')->where('id', input('id'))->find();
            $info['set_time'] = date("Y-m-d", $info['set_time']);
            $info['start_time'] = date("Y-m-d", $info['start_time']);
            $info['use_time'] = date("Y-m-d", $info['use_time']);
            $start_time = strtotime(date('Y-m-01',time()));
            $end_time = strtotime('+1 month',$start_time)-1;
            $year_month = strtotime(date('Y-m',time()));

                //月度人均积分
                //公司人员总数
                $people_sum = M('users')->where('com_id',$info['id'])->where('type',1)->count() -1;
                //公司当月获得总积分
                $where_a['a.status'] = 2;
                $where_a['a.prize_buckle_time'] = ['between',[$start_time,$end_time]];
                $where_a['c.is_cancellation'] = 0;//未作废
                $where_a['d.type'] = 1;//在职
                $where_a['d.role_id'] = ['neq',''];//排除管理员
                $where_a['a.com_id'] = $info['id'];
                $res = M('com_integral_prize_buckle a')
                    ->join('com_integral_prize_buckle_relation_event b','a.id=b.prize_buckle_id','right')
                    ->join('com_integral_event_relation_users c','c.event_id=b.id','right')
                    ->join('users d','c.user_id=d.id','left')
                    ->where($where_a)
                    ->field('COALESCE(SUM(IF(c.piece_rate=0,c.integral_b,c.piece_rate*c.integral_b)),0) integral_b ')
                    ->find();
                $total_integral = $res['integral_b'];
                //公司当月总奖扣人次
                $where_b = [];
                $where_b['a.com_id'] = $info['id'];
                $where_b['a.status'] = 2;
                $where_b['c.is_cancellation'] = 0;//未作废
                $where_b['a.prize_buckle_time'] = ['between',[$start_time,$end_time]];
                $total_prize_buckle_people_sum = M('com_integral_prize_buckle a')
                    ->join('com_integral_prize_buckle_relation_event b','b.prize_buckle_id = a.id','left')
                    ->join('com_integral_event_relation_users c','c.event_id = b.id','left')
                    ->where($where_b)->count('c.id');
                //月人均得分
                if(empty($people_sum)){
                    $average_integral = 0;
                    $average_sum = 0;
                }else{
                    $average_integral = ceil($total_integral/$people_sum);
                    //月人均人次
                    $average_sum = ceil($total_prize_buckle_people_sum/$people_sum);
                }

            $info['average_integral'] = $average_integral;
            $info['average_sum'] = $average_sum;

            $this->assign('info', $info);
        }
        return $this->fetch();
    }

    public function index_del(){
        $params = input();
        $ids = explode(',', $params['id']);
        $company_names = db('company')->where('id', 'in', $ids)->column('name');
        $company_names = implode(', ', $company_names);
        db('company')->where('id', 'in', $ids)->update(['is_del'=>1,'mobile'=>'','account'=>'','account_code'=>'']);
        add_sys_log('删除企业: '.$company_names);
        return $this->ajaxReturn(0, '成功');
    }
    //添加编辑企业提交
    public function index_store(){
        $params = input();
        if(count($params) == 2){
            //修改状态
            $r = db('company')->where('id', $params['id'])->update(['status'=>$params['status']]);
            $com_info = db('company')->where('id', $params['id'])->field('name')->find();
            add_sys_log('修改企业状态: '.$com_info['name']);
            return json_encode(['info'=>'成功', 'status'=>1]);
        }

        $result = $this->validate($params,'Company');
        if(true !== $result){
            return $this->ajaxReturn(1, $result);
        }
        $pattern = '/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{5,20}$/';
        if(!preg_match($pattern,$params['account_code'])){
            return $this->ajaxReturn(1, '企业代码必须为数字加字母组合');
        }
        $params['set_time'] = strtotime($params['set_time']);
        $params['start_time'] = strtotime($params['start_time']);
        $params['use_time'] = strtotime($params['use_time']);

        $com_exists_id = db('company')->where(['account'=>$params['account']])->whereOr(['account_code'=>$params['account_code']])->value('id');
        if($params['id']){
            if($com_exists_id != $params['id']){
                return $this->ajaxReturn(1, '添加失败 企业账号或企业代码已存在');
            }
//            unset($params['account']);
            Db::startTrans();
            try{
                $name = db('company')->where('id', $params['id'])->value('account');
                if($name != $params['account']){
                    M('users')->where(['com_id'=>$params['id'],'account'=>$name])->update(['account'=>$params['account']]);
                }
                db('company')->where('id', $params['id'])->update($params);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return $this->ajaxReturn(1, '操作失败');
            }
            add_sys_log('修改企业: '. $params['name']);
        }else{
            if($com_exists_id){
                return $this->ajaxReturn(1, '添加失败 企业账号或企业代码已存在');
            }
            $errMsg = '';
            $user_account_exists = db('users')->where(['account'=>$params['account']])->value('id');
            $user_account_exists && $errMsg = '企业用户账号已存在';
            $user_mobile_exists = db('users')->whereOr(['mobile'=>$params['mobile']])->value('id');
            $user_mobile_exists && $errMsg = '企业用户电话已存在';
            if($errMsg){
                return $this->ajaxReturn(1, $errMsg);
            }
            Db::startTrans();
            try{
                $params['create_time'] = time();
                $com_id = db('company')->insertGetId($params);
                $com_user_data = [
                    'com_id'=>$com_id,
                    'account'=>$params['account'],
                    'password'=>md5(123456),
                    'c_time'=>time(),
                    'mobile'=>$params['mobile'],
                    'name'=>$params['name'],
                    'job_number'=>$params['account_code'],
                    'is_sort'=>0,
                ];
                //添加管理员
                db('users')->insertGetId($com_user_data);
                //添加配置
                db('com_config')->insert(['com_id'=>$com_id]);
                add_sys_log('添加企业: '. $params['name']);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return $this->ajaxReturn(1, '操作失败');
            }
        }
        return $this->ajaxReturn(0,"成功", url(CONTROLLER_NAME.'/index'));
    }

    public function index_explode($where){
        set_time_limit(0);

        $list = db('company')->where($where)->order('id desc')->select();
        $addr_ids = array_unique(array_merge(array_column($list, 'province_id'), array_column($list, 'city_id'), array_column($list, 'area_id')));
        $region_list = db('region')->where('id', 'in', $addr_ids)->column('id, name');
        $trade_list = db('trate')->order('id desc')->column('id, name, status'); //行业类目
        $manage_list = db('manage')->order('id desc')->column('id, name, status'); //经营类目

        $strTable = '<table width="500" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:*">企业名称</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:*">企业账号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">所在地区</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">对接人</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">对接人电话</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">所属行业</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">经营类型</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">启动日期</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">剩余时间</td>';
        $strTable .= '</tr>';
        if (!empty($list)) {
            foreach ($list as $key => $val) {
                $expire_time = date('Y-m-d',strtotime("+".$val['use_time']."year",$val['start_time']));
                $r_time = strtotime($expire_time) - $val['start_time'];
                $r_time = time_to_str($r_time); //剩余时间
                $city = isset($region_list[$val['city_id']])?$region_list[$val['city_id']]:'';
                $area_id = isset($region_list[$val['area_id']])?$region_list[$val['area_id']]:'';
                $trade = isset($trade_list[$val['trade_id']]['name'])?$trade_list[$val['trade_id']]['name']:'';
                $manage = isset($manage_list[$val['manage_id']]['name'])?$manage_list[$val['manage_id']]['name']:'';
                $strTable .= '<tr>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['name'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['account'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . "{$region_list[$val['province_id']]}-{$city}-{$area_id}" . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['docking_people'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['docking_mobile'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $trade . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $manage . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . date('Y-m-d',$val['start_time']) . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $r_time . '</td>';
                $strTable .= '</tr>';
            }
        }
        $strTable .= '</table>';
        unset($list);
        $name = '企业列表';
        downloadExcel($strTable, $name);
        exit();
    }
    //添加企业管理员页面
    public function index_add_account(){
        $id = input('id');
        $info = db('users')->where('com_id', $id)->find();
        if($info){
            $this->error("该企业已添加管理员 {$info['account']}");
        }
        $this->assign('id', $id);
        return $this->fetch();
    }
    //保存企业管理员
    public function index_save_account(){
        $data = input();
        $result = $this->validate(
            $data,
            [
                'name|姓名'  => 'require|max:50',
                'account|账号'   => 'require|max:50',
                'mobile|手机号码'   => 'require|max:15',
                'password|密码'   => 'require|max:50'
            ]);
        if(true !== $result){
            return $this->ajaxReturn(1, $result);
        }
        $info = db('users')->where('com_id', $data['com_id'])->find();
        if($info){
            return $this->ajaxReturn(1, '添加失败 该企业已存在管理员');
        }
        $info = db('users')->where('name', $data['name'])->find();
        if($info){
            return $this->ajaxReturn(1, '添加失败 姓名已存在');
        }
        $info = db('users')->where('account', $data['account'])->find();
        if($info){
            return $this->ajaxReturn(1, '添加失败 账号已存在');
        }
        $info = db('users')->where('mobile', $data['mobile'])->find();
        if($info){
            return $this->ajaxReturn(1, '添加失败 手机号码已存在');
        }
        $data['password'] = md5($data['password']);
        $data['c_time'] = time();
        db('users')->insert($data);
        return $this->ajaxReturn(0, '添加成功', url('company/index'));
    }

    /**
     * 企业注册记录
     */
    public function reg_index(){
        $where = [];
        $status = input('status', -1);
        if($status != -1){
            $where['status'] = $status;
        }
        $list = db('company_log')->where($where)->order('id desc')->paginate('',false,page_param());
        $this->assign('list', $list);
        return $this->fetch();
    }
    //企业状态修改
    public function reg_index_up(){
        $id = input('id');
        $info = db('company_log')->where('id', $id)->find();
        if($info['status'] == 1){
            return json_encode(['info'=>'该记录已处理', 'status'=>0]);
        }else{
            db('company_log')->where('id', $id)->update(['status'=>1]);
            return json_encode(['info'=>'已处理', 'status'=>1]);
        }
    }
    public function reg_del(){
        $idArr = explode(',', I('id', 0));
        $res = M('company_log')->where('id','in',$idArr)->delete();
        if($res){
            return $this->ajaxReturn(0,'删除成功');
        }else{
            return $this->ajaxReturn(0, '删除失败');
        }
    }

}